home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1990: Night of the Living Disc / Night of the Living Disc.hdv / Dev.CD.5 / develop / develop.2 / P118.121.CPlusO < prev    next >
Encoding:
Text File  |  1990-03-13  |  18.1 KB  |  319 lines  |  [04] ASCII Text (0x0000)

  1. USING C++ OBJECTS IN A HANDLE-BASED WORLD
  2.  
  3. Although C++ is a powerful and flexible language, its image of the world inside your computer was shaped by operating systems that were a bit more "traditional" than the Macintosh's. As a result, C++ routines that work fine for MPW tools can cause severe problems when used in a Macintoshr application. But there are ways around these problems. This article describes a technique that allows you to use normal C++ objects in your Macintosh applications without undue discomfort.
  4.  
  5. Using C++ objects in the handle-based world of the Macintosh Memory Manager can get pretty tricky at times. The Apple extension to C++ that solves the memory allocation problems you're bound to run into can create other headaches for you if you need to use one or more of several important C++ features in your program. In this article, you'll learn about the memory allocation problems you can expect to encounter when you create objects in C++. You'll also learn how to get around these problems while still retaining the use of important C++ features, by creating a 
  6. special class PtrObject. You'll see a sample program that uses PtrObject, and you'll learn how to implement the class.
  7.  
  8. Problems with Memory Allocation for Objects in C++
  9.  
  10. In C++, objects are created dynamically with the new operator, and disposed of with the delete operator when you've finished with them, like this:
  11.  
  12. TMyObject* aMyObjectRef;
  13. aMyObjectRef = new TMyObject;   // Create a TMyObject object.
  14. aMyObject->AReallyCoolRoutine();        // Do something useful...
  15. delete aMyObject;                       // Delete the object.
  16.  
  17. When you use these operators, C++ transforms them into calls to operator new and operator delete. The default versions of operator new and operator delete provided in the C++ library use the C Standard Library routines malloc and free, respectively, to allocate and deallocate the memory needed to store the object. (Actually, the calloc routine is called to allocate the memory, but calloc just turns around and calls malloc to do the real work.) 
  18.  
  19. These routines work fine for MPWr tools, but they can cause the following severe problems when used in a Macintosh application:
  20. o       Heap fragmentation. Nonrelocatable memory for your objects can be allocated in the middle of your heap, preventing the Mac's Memory Manager from compacting memory properly.
  21. o       Heap space permanently wasted. Because malloc and free manage their own list of free memory blocks and never return unused space to the Mac's Memory Manager, if you create a lot of C++ objects your program can run out of memory and crash even though you have plenty of free memory available. (See the sidebar "Everything You Didn't Want to Know About Malloc and Free" for more information on malloc internals.)
  22. Fortunately, you can override the default versions of operator new and operator delete in your own classes to get explicit control over memory allocation. To help you do this, Apple extended C++ to include a predefined base class called HandleObject. If classes you define inherit from HandleObject, the Mac's NewHandle and DisposHandle traps are called instead of the default operator new and operator delete routines. 
  23.  
  24. While this solves the memory problems just mentioned, it also precludes the use of several important C++ features. Here is a partial list of the restrictions that apply when classes you define inherit from HandleObject: 
  25.  
  26. o       It is an error to declare global variables, local variables, arrays, members, or parameters of handle-based classes (rather than pointers to them).
  27. o Multiple inheritance cannot be used with handle-based classes.
  28. o       Handle-based objects can be created only by the new operator. The only use of a dereferenced handle-based class pointer (for example, *x) is to refer to a field in the class (for example, *x.y or x->y).
  29. o It is not possible to allocate an array of handle-based objects-for example, new->MyObjects[10].
  30.  
  31. As you can see, there are quite a few useful things you can't do in C++ if you use HandleObject. Most programs should be able to live with these restrictions, but    if your program needs to use multiple inheritance or arrays of objects, a different solution is called for.
  32.  
  33. Everything You Didn't Want to Know 
  34. About Malloc and free
  35.  
  36. Why do the malloc and free routines wreak so much havoc in a Macintosh application? The main reason is that these routines were originally written for UNIX systems, which have no built-in memory allocation facilities. So these library routines ended up doing everything themselves, including free list management. 
  37.  
  38. This isn't all bad, since these routines are simpler and faster than their Macintosh Memory Manager equivalents, but they can cause the severe problems listed earlier in this article for a Macintosh application. The worst part is that these problems can occur even if your application doesn't call malloc directly. In many situations, C++ calls malloc for you, as do many of the other routines in the standard library. 
  39.  
  40. Here's how it all works (in MPW, at least):
  41.  
  42. When you request some memory from malloc, it rounds the size up to the nearest power of 2 (8-byte minimum, ID checked at the door). If you ask for more than 2048 bytes, malloc just calls NewPtr to allocate the memory, and DisposPtr to get rid of it. Otherwise, malloc checks its internal free list looking for blocks of the specified size. If it doesn't find any blocks of that size, it allocates a chunk of memory with NewPtr big enough to hold 2K worth of blocks (plus 2 bytes overhead per block), and adds the new blocks to the free list for that size. It then returns you the first block off of the free list.
  43.  
  44. When you dispose of memory with the free routine, it looks at the block header to determine which free list to put the block in, and inserts it into the list (sorted by block address to allow for more intelligent freestore management in the future). Here's what a small free list looks like:
  45.  
  46.  
  47. THE SOLUTION: CREATING A SPECIAL CLASS PtrObject
  48. The solution to memory allocation problems when you can't use HandleObject is to create a special class PtrObject analogous to the HandleObject class. This class overrides both operator new and operator delete, so that real Memory Manager pointers are used instead of the pointers returned by the default operator new.  PtrObject also supports the allocation of objects into a separate heap, which further reduces memory fragmentation.
  49.  
  50. The method functions of the class PtrObject are as follows:
  51.  
  52. AllocHeap               This function creates a separate heap. All descendants of class PtrObject created after calling this function will use this heap. If you do not call this function in your program, the default (application) heap will be used.
  53.  
  54. DisposeHeap             This function disposes of the heap allocated by a previous call to AllocHeap. You should call this function before quitting your application. Any PtrObjects created inside the heap will be invalid, so make sure that you aren't using any of those objects anymore (neither operator delete nor the destructor for these objects will be called).
  55.  
  56. FreeMemory              This function returns the amount of free space in the PtrObject heap, as returned by the trap FreeMem. If no 
  57. separate heap exists, this function will return the amount of free memory in the default (application) heap.
  58.  
  59. MaxMemory               This function returns the size of the largest free block in 
  60. the PtrObject heap, as returned by the trap MaxMem. If no separate heap exists, this function will return the amount of free memory in the default (application) heap.
  61.  
  62. operator new            This function is called by the C++ compiler to allocate memory for PtrObjects. You never need to call it directly.
  63.  
  64. operator delete         This function is called by the C++ compiler to deallocate memory used by PtrObjects. You never need to call it directly.
  65.  
  66. Here is the class declaration for PtrObject, which would normally be found in the header file PtrObject.h.
  67.  
  68. class PtrObject {
  69. public:
  70.         static OSErr    AllocHeap(size_t heapSize);
  71.         // Create a heap heapSize bytes long to allocate
  72.         // objects in.
  73.         
  74.         static void     DisposeHeap();
  75.         // Free up the heap allocated by a previous call
  76.         // to AllocHeap.
  77.  
  78.         static long     FreeMemory();
  79.         // Return the total amount of free space in the heap.
  80.  
  81.         static Size     MaxMemory();
  82.         // Return the size of the largest free block in the heap.
  83.         
  84.         void*           operator new(size_t size);
  85.         void            operator delete(void* p);
  86.         // These are our special allocation and
  87.         // deallocation operators.
  88.  
  89. private:
  90.         static THz      fZone;  
  91.         // Our private zone pointer.
  92. };
  93.  
  94.  
  95. Notice that the AllocHeap, DisposeHeap, FreeMemory, and MaxMemory calls are all static member functions, and that the fZone variable is a static data member. In C++, static members are shared across all instances of a class. You should use static members in place of global variables and functions whenever possible, since they have limited scope (which means fewer name conflicts) and they are logically tied to the class in which they are declared (which means more readable source code). To call a static member function, the syntax is
  96.  
  97. ClassName::StaticFunctionName(/* parameters, if any */);
  98.  
  99. A SAMPLE PROGRAM USING PtrObject
  100. Now that you've seen the interface to the PtrObject class, here is a small sample application that uses it. This program isn't very useful-all it does is define a subclass of PtrObject, create an instance of that object, and call one of its methods.
  101.  
  102. The first thing we have to do is the standard setup for a Macintosh application, which in this case means including all of the needed header files for the Macintosh Toolbox and the C Standard Library:
  103.  
  104. // TestPtrObject.cp
  105. #include <Types.h>
  106. #include <QuickDraw.h>
  107. #include <Fonts.h>
  108. #include <SegLoad.h>
  109. #include <Events.h>
  110. #include <Windows.h>
  111. #include <Menus.h>
  112. #include <TextEdit.h>
  113. #include <Dialogs.h>
  114. #include <Memory.h>
  115. #include <OSUtils.h>
  116. #include <stdio.h>
  117. #include <string.h>
  118. #include <stddef.h>
  119.  
  120. Next we include the header file for the PtrObject class (just shown), and define a 
  121. new class TLout that is derived from it:
  122.  
  123. #include "PtrObject.h"
  124.  
  125. // A small class that contains some data and a constructor,
  126. // but spends all of its time on street corners cadging
  127. // cigarettes instead of doing useful work.
  128.  
  129. class TLout : public PtrObject {
  130. public:
  131.         TLout() { DoCadge(); }; // Our constructor.
  132.         virtual void    DoCadge();      // A rude member function.
  133. private:
  134.         char            fArray[256];
  135. };
  136.  
  137. void TLout::DoCadge()
  138. {
  139.         strcpy(fArray,"Hey buddy, spare a cig?");
  140. }
  141.  
  142. That's all it takes to define a class with the correct memory management behavior. Here is the main 
  143. program, which uses our newly defined TLout class:
  144.  
  145. void InitToolbox();             // Forward declaration.
  146.  
  147. main()
  148. {
  149.         // We need this much space to store the objects
  150.         // we're going to initialize - in this case, 16KBytes.
  151.         const size_t kDefaultHeapSize = 0x4000;
  152.         
  153.         InitToolbox();  // Initialize Mac Toolbox (ho hum).
  154.         
  155.         // Create a heap for PtrObjects to live in.
  156.         OSErr heapErr = PtrObject::AllocHeap(kDefaultHeapSize);
  157.         
  158.         // If we got an error, quit - this isn't a real
  159.         // application, so we don't need error handling, right?
  160.         if (heapErr != noErr)
  161.            ExitToShell();       
  162.  
  163.         // Create an object - will go in separate heap automatically.
  164.         TLout* aLout = new TLout;       // Do that voodoo that TLouts do.
  165.         if (aLout != nil)
  166.          {
  167.             aLout->DoCadge();
  168.             delete aLout;               // Delete our object now that we have finished with it.
  169.          }
  170.  
  171.         // Dispose of the heap.
  172.         PtrObject::DisposeHeap();
  173.         ExitToShell();
  174. }
  175.  
  176. One important thing needs to be pointed out here: you need to call PtrObject::AllocHeap as early in 
  177. your program as possible, or the newly created heap may fragment your application heap.
  178.  
  179. Finally, just for completeness, here's the implementation of the InitToolbox routine, which makes sure 
  180. that all of the necessary pieces of the Mac Toolbox are initialized:
  181.  
  182. void InitToolbox()
  183. {
  184.         // Standard Macintosh initialization.
  185.         InitGraf((Ptr) &qd.thePort);
  186.         InitFonts();
  187.         InitWindows();
  188.         InitMenus();
  189.         TEInit();
  190.         InitDialogs(nil);
  191.         InitCursor();
  192.         MaxApplZone();
  193. }
  194.  
  195. IMPLEMENTING PtrObject
  196. Now that we've seen how to use class PtrObject, we need to implement it. We must first include all the necessary header files and allocate our static member data:
  197.  
  198. // PtrObject.cp
  199. #include <Memory.h>
  200. #include <Errors.h>
  201. #include <stdio.h>
  202. #include <stddef.h>
  203. #include "PtrObject.h"
  204.  
  205. // Static data members actually need to be declared outside of the class 
  206. // definition in order to have space allocated.
  207. THz PtrObject::fZone = nil;
  208.  
  209. Next we have the AllocHeap function.
  210.  
  211. OSErr PtrObject::AllocHeap(size_t heapSize)
  212. {
  213.         // By default, the heap gets kNumDfltMasters master pointers. A small number,
  214.         // but it shouldn't matter, since we will only be allocating Ptrs in this heap,                 // and Ptrs don't use master pointers. 
  215.         const short kNumDfltMasters = 16;
  216.  
  217.         // This magic number from Inside Mac, vol. II, chapter 1, is the amount of space 
  218.         // required for the zone header and trailer, and the master pointer block. We add               // this to the requested heap size to compensate.
  219.         const size_t kZoneOverhead = 64 + 8 + (sizeof(long) * kNumDfltMasters);
  220.  
  221.         heapSize += kZoneOverhead;              // Factor in overhead.
  222.  
  223.         // Allocate space for the zone.
  224.         Ptr zonePtr = NewPtr(heapSize); 
  225.         if (!zonePtr)                   // If alloc fails, return error.
  226.             return MemError();  // Get a pointer to the end of the heap.
  227.  
  228.         Ptr limitPtr = (Ptr) (((ptrdiff_t) zonePtr) + heapSize);
  229.         
  230.         // Initialize the zone.
  231.         InitZone(nil, kNumDfltMasters, limitPtr, zonePtr);
  232.  
  233.         // Save the zone pointer in our static class variable.
  234.         fZone = (THz) zonePtr;
  235.         return noErr;
  236. }
  237.  
  238. The DisposeHeap member function is much simpler. It just checks to see if we allocated a zone in the past, and if so, it disposes of the heap's memory. This will destroy any objects that were allocated inside the heap, which could be dangerous, so be careful when you call this routine.
  239. void PtrObject::DisposeHeap()
  240. {
  241.         // If zone actually exists, dispose of it.
  242.         if (fZone)
  243.          {
  244.             DisposPtr((Ptr) fZone);
  245.             fZone = nil;
  246.          }
  247. }
  248.  
  249. Next we have the FreeMemory and MaxMemory functions. We'll show them together, since they are almost 
  250. identical. The only thing of note here is the way we switch in our special heap if it exists.
  251.  
  252. long PtrObject::FreeMemory()
  253. {
  254.         THz savedZone;
  255.                                                 // Before we can return the amount of free 
  256.                                                 // memory, we need to switch to the correct zone.
  257.         if (fZone)
  258.          {
  259.             savedZone = GetZone();              // Save current zone.
  260.             SetZone(fZone);                     // Make our zone current.
  261.          }
  262.  
  263.         long free = FreeMem();          // Get total free space.
  264.  
  265.         if (fZone)
  266.           SetZone(savedZone);           // Restore previous zone.
  267.         return free;
  268. }
  269.  
  270. Size PtrObject::MaxMemory()
  271. {
  272.         THz savedZone;
  273.                                                 // Before we can return the maximum block size,                                                         // we need to switch to the correct zone.
  274.         if (fZone)
  275.          {
  276.             savedZone = GetZone();              // Save current zone.
  277.             SetZone(fZone);                     // Make our zone current.
  278.          }
  279.  
  280.         Size tSize;                             // We know the heap can't grow,
  281.                                                 // but we have to have a temp
  282.                                                 // variable to satisfy the Toolbox.
  283.         Size max = MaxMem(&tSize);              // Get size of biggest block.
  284.         if (fZone)
  285.           SetZone(savedZone);           // Restore previous zone.
  286.         return max;
  287. }
  288. Now we get to the heart of the class, the operator new function. Like the FreeMemory call, operator new switches to our private heap before it actually allocates memory, and restores the previous heap when it is done. 
  289. The actual memory allocation is done by a call to everyone's favorite Macintosh trap, NewPtr.
  290.  
  291. void* PtrObject::operator new(size_t size)
  292. {
  293.         THz savedZone;
  294.  
  295.         // Before we can allocate memory, we need to switch to the correct zone.
  296.         if (fZone)
  297.          {
  298.             savedZone = GetZone();              // Save current zone.
  299.             SetZone(fZone);                     // Make our zone current.
  300.          }
  301.         Ptr p = NewPtr(size);           // Allocate memory for object.
  302.         if (fZone)
  303.           SetZone(savedZone);           // Restore previous zone.
  304.         return p;
  305. }
  306.  
  307. Last, we have the operator delete function. All it does is dispose of the memory occupied by the object. We don't need to swap in the private heap here, since the Memory Manager keeps track of the heap that the pointer belongs to for us.
  308.  
  309. void PtrObject::operator delete(void* p)
  310. {
  311.         DisposPtr((Ptr) p);                     // This works regardless of the zone
  312.                                                 // the pointer was allocated in.
  313. }
  314.  
  315. That's all there is to the PtrObject class. If you wish to explore the stranger side of C++ (multiple inheritance 
  316. and so on), you should use it, since it allows your creations to live in the complicated world of the Macintosh Memory Manager.
  317.  
  318. ---------------
  319. Andy Shebanow, a DTS engineer, wrote this article for the best of reasons: "The beer people had their say in the last issue, and it's about time the Mountain Dew people spoke up." His highly developed personal skills have earned him the affectionate nickname "The Shebanator." After working for a medical imaging company, he joined Apple twenty-odd months ago. It's been so long since he was outside that he's forgotten what his hobbies are; he vaguely remembers something about driving cars at excessive and/or illegal speeds.